const url = require("url");
const Server = function () {
    const G = this;

    this._get = {};
    this._post = {};

    const app = function (req, res) {
        let pathName = url.parse(req.url).pathname;

        const method = req.method.toLowerCase();


        if (!pathName.endsWith("/")) {
            pathName += "/"
        }


        if (G["_" + method][pathName]) {

            if (method === "post") {
                let postStr = "";
                res.on("data", function (chunk) {
                    postStr += chunk;


                });
                res.end("end", function (err, chunk) {
                    req.body = postStr;
                    G["_" + method][pathName](req, res);
                })


            } else {
                G["_" + method][pathName](req, res);

            }

        } else {
            res.end("路由不存在")
        }
    };

    app.get = function (string, callback) {

        if (!string.endsWith('/')) {
            string += "/"
        }

        if (!string.startsWith('/')) {
            string = "/" + string
        }

        G._get[string] = callback;
    };
    app.post = function (string, callback) {

        if (!string.endsWith('/')) {
            string += "/"
        }

        if (!string.startsWith('/')) {
            string = "/" + string
        }

        G._post[string] = callback;
    };
    return app;
};
module.exports = Server();